package com.example.demo.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * zookeeper分布式锁工具类
 */
@Component
public class ZookeeperLockUtil {

    public static void getZookeeperLock(CuratorFramework curatorFramework, String lockPath){
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);
        new Thread(new TestThread(1,lock)).start();
    }

    static class TestThread implements Runnable {
        private Integer threadFlag;
        private InterProcessMutex lock;

        public TestThread(Integer threadFlag, InterProcessMutex lock) {
            this.threadFlag = threadFlag;
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                lock.acquire();
                System.out.println("当前锁所有节点： " + lock.getParticipantNodes());
                System.out.println("第"+threadFlag+"线程获取到了锁");
                //等到5秒后释放锁
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("分布式锁2 调用完成");
        }
    }
}
